<template>
  <div>
    <div>
      <div class="flex justify-between items-center px-20px pt-20px">
        <p class="">我发布的需求</p>
        <el-button
          icon="el-icon-plus"
          type="primary"
          plain
          size="small"
          @click="onIssue"
        >发布需求</el-button>
      </div>
      <el-divider></el-divider>
      <div class="card">
        <el-tabs
          v-model="activeName"
          @tab-click="tabClick"
          type="border-card"
          class="mx-10px mb-30px"
        >
          <el-tab-pane
            :label="item.dictLabel"
            :name="item.dictValue"
            v-for="(item, index) in requireApplyStatus"
            :key="index"
          >
            <el-table
              v-loading="tableLoading"
              :data="tableList"
              style="width: 100%"
            >
              <el-table-column
                prop="requirementId"
                label="需求编号"
                width="200"
              ></el-table-column>
              <el-table-column
                prop="requirement"
                label="需求名称"
                width="200"
              ></el-table-column>
              <el-table-column
                label="申请时间"
                prop="requirement"
                width="180"
              >
                <template slot-scope="{ row }">
                  {{ formatDate(row.applyTime) }}
                </template>
              </el-table-column>
              <el-table-column
                label="发布时间"
                prop="publishTime"
                width="180"
              >
                <template slot-scope="{ row }">
                  {{ row.publishTime ? formatDate(row.publishTime) : '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="status"
                label="发布状态"
              >
                <template slot-scope="scope">
                  <span
                    v-if="scope.row.status == 0"
                    class="text-[#f56c6c]"
                  >待处理</span>
                  <span
                    v-if="scope.row.status == 1"
                    class="text-[#67c23a]"
                  >已发布</span>
                  <div
                    v-if="scope.row.status == 2"
                    class="flex flex-col gap-4px"
                  >
                    <span class="text-[#f56c6c]">退回修改</span>
                    <el-tooltip
                      :content="scope.row.finalComment || scope.row.firstComment"
                      placement="top"
                    >
                      <p class="m-0 text-[12px] text-[#666] line-clamp-2 cursor-pointer">{{ scope.row.finalComment || scope.row.firstComment }}</p>
                    </el-tooltip>
                  </div>
                  <span
                    v-if="scope.row.status == 3"
                    class="text-[#f56c6c]"
                  >审核不通过</span>
                  <span
                    v-if="scope.row.status == 4"
                    class="text-[#e6a23c]"
                  >待审核</span>
                  <span
                    v-if="scope.row.status == 5"
                    class="text-[#f56c6c]"
                  >关闭需求</span>
                </template>
              </el-table-column>
              <el-table-column
                label="响应状态"
                prop="serviceCount"
                width="150"
              >
                <template slot-scope="{ row }">
                  目前已有{{ row.serviceCount }} 企业对接
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="200px"
              >
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.status == 0 || scope.row.status == 2"
                    type="text"
                    @click="btnClick(scope.row, scope.$index, 'edit')"
                  >编辑</el-button>
                  <el-button
                    type="text"
                    @click="btnClick(scope.row, scope.$index, 'view')"
                  >查看</el-button>
                  <el-button
                    v-if="scope.row.status == 0 || scope.row.status == 2"
                    type="text"
                    @click="btnClick(scope.row, scope.$index, 'delete')"
                  >关闭</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="flex justify-end mt-15px">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageData.currentPage"
                :page-sizes="[10, 20, 30, 40, 50]"
                :page-size="pageData.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageData.totalPage"
              >
              </el-pagination>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 需求上架 -->
    <el-dialog
      :title="type == 'view'?'需求详情':'发布需求'"
      width="1000px"
      :visible="issueDialogVisible"
      @close="handleDialogClose"
    >
      <el-form
        :rules="serviceRules"
        ref="serviceForm"
        :model="serviceData"
        size="medium"
        label-width="120px"
        :disabled="type == 'view'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="需求企业"
              prop="companyName"
            >
              <el-input
                v-model="serviceData.companyName"
                disabled
                placeholder="请输入需求企业"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="联系电话"
              prop="userPhoneNum"
            >
              <el-input
                v-model="serviceData.userPhoneNum"
                disabled
                placeholder="请输入联系电话"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="需求类型"
              prop="requirementTypeId"
            >
              <el-select
                v-model="serviceData.requirementTypeId"
                placeholder="请选择需求类型"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in purchases"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="需求名称"
              prop="requirement"
            >
              <el-input
                placeholder="请输入需求名称，如：年采购 1000 吨高精度铝箔、寻求新能源汽车电机组装代工"
                v-model="serviceData.requirement"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="需求详情"
              prop="requirementDesc"
            >
              <el-input
                type="textarea"
                :rows="5"
                placeholder="请输入需求详情，包括规格、数量等信息"
                v-model="serviceData.requirementDesc"
                minlength="50"
                maxlength="2000"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="合作方要求"
              prop="partnerRequirements"
            >
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入对合作方的要求，如：需具备广西本地生产资质、优先考虑柳州周边企业"
                v-model="serviceData.partnerRequirements"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="预算金额(元)"
              prop="budget"
            >
              <el-input
                v-model="serviceData.budget"
                placeholder="请输入预算金额(元)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="交付时间"
              prop="deliveryTime"
            >
              <el-date-picker
                v-model="serviceData.deliveryTime"
                type="date"
                placeholder="请选择交付时间"
                style="width: 100%;"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <div
            class="submit_box"
            v-if="type == 'edit'"
          >
            <el-button
              type="primary"
              v-loading="applyBtnLoading"
              style="width: 120px;margin-left: 20px;"
              @click="saveOrApplyProduct()"
            >申请发布需求
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  requirementPublish,
  requirementEdit,
  requirementPagePrivate,
  getRequirementetail,
  requirementClose,
} from "@/api/home";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      activeName: "all",
      requireApplyStatus: [
        { dictLabel: "全部", dictValue: "all" },
        { dictLabel: "待处理", dictValue: "0" },
        { dictLabel: "已发布", dictValue: "1" },
        { dictLabel: "退回修改", dictValue: "2" },
        { dictLabel: "审核不通过", dictValue: "3" },
        { dictLabel: "待审核", dictValue: "4" },
        { dictLabel: "关闭需求", dictValue: "5" },
      ],
      pageData: {
        currentPage: 1,
        pageSize: 6,
        totalPage: 0,
      },
      tableLoading: false,
      tableList: [],
      serviceData: {
        partnerRequirements: "",
        deliveryTime: "",
      },
      serviceRules: {
        requirement: [
          { required: true, message: "请输入需求名称", trigger: "blur" },
        ],
        requirementTypeId: [
          { required: true, message: "请选择需求类型", trigger: "change" },
        ],
        productTypeId: [
          { required: true, message: "请选择产品类型", trigger: "change" },
        ],
        requirementDesc: [
          { required: true, message: "请输入需求详情", trigger: "blur" },
        ],
        partnerRequirements: [
          { required: true, message: "请输入合作方要求", trigger: "blur" },
        ],
        budget: [
          { required: true, message: "请输入预算金额", trigger: "blur" },
        ],
        deliveryTime: [
          { required: true, message: "请选择交付时间", trigger: "change" },
        ],
      },
      applyBtnLoading: false,
      issueDialogVisible: false,
      type: "edit",
    };
  },
  computed: {
    ...mapGetters("user", ["userInfo"]),
    ...mapGetters("dicts", ["cityDict", "getDictByParamsKey"]),
    purchases() {
      return this.getDictByParamsKey({ parentId: 4 });
    },
    types() {
      return this.getDictByParamsKey({ parentId: 2 });
    },
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    onIssue() {
      // 初始化表单数据
      this.serviceData = {
        needQuote: 1,
        budget: "",
        companyName: this.userInfo.nickName,
        userPhoneNum: this.userInfo.userPhoneNum,
        partnerRequirements: "",
        deliveryTime: "",
      };
      this.type = "edit";
      this.issueDialogVisible = true;
    },
    formatDate(date) {
      if (!date) return "--";
      // 格式化日期为 YYYY-MM-DD HH:mm:ss
      const d = new Date(date);
      const year = d.getFullYear();
      const month = ("0" + (d.getMonth() + 1)).slice(-2);
      const day = ("0" + d.getDate()).slice(-2);
      const hours = ("0" + d.getHours()).slice(-2);
      const minutes = ("0" + d.getMinutes()).slice(-2);
      const seconds = ("0" + d.getSeconds()).slice(-2);
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    tabClick(val) {
      if (val.name === "all") {
        this.getTableList();
      } else if (val.name === "0") {
        this.getTableList(0);
      } else if (val.name === "1") {
        this.getTableList(1);
      } else if (val.name === "2") {
        this.getTableList(2);
      } else if (val.name === "3") {
        this.getTableList(3);
      } else if (val.name === "4") {
        this.getTableList(4);
      } else if (val.name === "5") {
        this.getTableList(5);
      }
    },
    handleSizeChange(val) {
      this.$set(this.pageData, "pageSize", val);
      this.getTableList();
    },
    handleCurrentChange(val) {
      this.$set(this.pageData, "currentPage", val);
      this.getTableList();
    },
    getTableList(status = "") {
      this.tableLoading = true;
      requirementPagePrivate({
        pageNo: this.pageData.currentPage,
        pageNum: this.pageData.pageSize,
        status,
      })
        .then((res) => {
          if (res.code === 200) {
            this.tableList = [...res.rows];
            this.pageData.totalPage = res.total;
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    btnClick(row, index, type) {
      switch (type) {
        case "edit":
          this.getDetail(row);
          break;
        case "view":
          this.getDetail(row);
          break;
        case "delete":
          this.$confirm("此操作将关闭该需求, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            requirementClose({ requirementId: row.requirementId }).then(
              (res) => {
                if (res.code === 200) {
                  this.$message.success("需求关闭成功");
                  this.getTableList();
                }
              }
            );
          });
          break;
        default:
          break;
      }
      this.type = type;
    },
    getDetail(row) {
      getRequirementetail({ requirementId: row.requirementId }).then((res) => {
        this.serviceData = res.data;
        this.serviceData.productTypeId = res.data.productType;
        this.issueDialogVisible = true;
      });
    },
    // 对话框关闭时的处理
    handleDialogClose() {
      this.issueDialogVisible = false;
      this.$refs.serviceForm.resetFields();
      // 清空上传的文件
      this.$set(this.serviceData, "productImg", "");
      this.fileList = [];
      if (this.$refs.imageUpload) {
        this.$refs.imageUpload.clearFiles();
      }
    },
    // 产品暂存或者上架
    saveOrApplyProduct() {
      this.$refs["serviceForm"].validate((valid) => {
        if (valid) {
          if (this.serviceData.status === 2) {
            this.applyBtnLoading = true;
            requirementEdit(this.serviceData)
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success("需求编辑成功");
                  this.getTableList();
                  this.handleDialogClose();
                }
              })
              .finally(() => {
                this.applyBtnLoading = false;
              });
          } else {
            this.applyBtnLoading = true;
            requirementPublish(this.serviceData)
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success("需求发布成功");
                  this.getTableList();
                  this.handleDialogClose();
                }
              })
              .finally(() => {
                this.applyBtnLoading = false;
              });
          }
        }
      });
    },
  },
};
</script>

<style scoped>
p {
  margin: 0;
  padding: 0;
}

:deep(.el-divider--horizontal) {
  margin: 12px 0;
}

:deep(.el-menu--horizontal > .el-menu-item.is-active) {
  border-bottom-color: #d32521;
}

:deep(.el-table thead) {
  color: #000;
}
</style>